package com.yyfax.ph.common.imageselector.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.yyfax.common.CLog;
import com.yyfax.ph.R;
import com.yyfax.ph.common.widgets.photoview.PhotoView;
import com.yyfax.ph.common.widgets.photoview.PhotoViewAttacher.OnViewTapListener;

import java.util.List;

public class PhotoViewAdapter extends PagerAdapter {

	static final String TAG = "PhotoViewAdapter";

	private List<String> mPicUrls;
	private Context mContext;
	private RequestManager mRequestManager;

	public PhotoViewAdapter(Context ctx, List<String> picUrl) {
		mContext = ctx;
		mPicUrls = picUrl;
		mRequestManager = Glide.with(ctx);
	}

	@Override
	public int getCount() {
		return null == mPicUrls ? 0 : mPicUrls.size();
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@Override
	public View instantiateItem(ViewGroup container, final int position) {
		if (null == mPicUrls) {
			return null;
		}
		PhotoView photoView = new PhotoView(container.getContext());
		String filepath = mPicUrls.get(position);
		mRequestManager.load(filepath).error(R.drawable.mis_skin_icon_img_load_fail).fitCenter().into(photoView);

		container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

		photoView.setOnViewTapListener(new OnViewTapListener() {
			@Override
			public void onViewTap(View view, float x, float y) {
				if (null != mClickListener) {
					mClickListener.onClick(view);
				}
			}
		});
		return photoView;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		CLog.i(TAG, "预览图片--destroyItem=");
		PhotoView photoView = (PhotoView) object;
		if (null == photoView)
			return;
		Glide.clear(photoView);
		Glide.get(mContext).clearMemory();
		container.removeView(photoView);
	}

	private OnItemClickListener mClickListener;

	public OnItemClickListener getOnItemClickListener() {
		return mClickListener;
	}

	public void setOnItemClickListener(OnItemClickListener mClickListener) {
		this.mClickListener = mClickListener;
	}

	interface OnItemClickListener {
		void onClick(View view);
	}

}
